<?php

class Spcode {
	
	// SimplyPost required class variables
	var $description	= 'Enables forum code such as [b], [i] or [url].  Secures all input.';
	var $version		= '0.2';
	
	function Spcode()
	{
		log_message('debug', 'SPCode plugin loaded.');
	}
	
	function install()
	{
		// Enable by default
		
		$CI =& get_instance();
		$CI->db->where('name', 'spcode');
		$CI->db->update('plugins', array('enabled' => 1));
	}
	
	function pre_edit($text)
	{
		// Old php versions used <br> new use <br /> ...
		$rep = nl2br("\n");
		$text = str_replace($rep, "\n", $text);
		
		return $text;
	}

	function post_submit($text)
	{
		// Need to allow them in case of edits
		$br = nl2br("\n");
		$allowed = '<strong><b><i><em><a>'.$br;
		
		$text = strip_tags($text, $allowed);
		$text = nl2br($text);
		
		// CI Requires 'http://' for external links, so we force it.
		$link1 = '/<a href="(.+?)">(.+?)<\/a>/si';
		$link2 = '/\[url=(.+?)\](.+?)\[\/url\]/si';
		$text = preg_replace_callback($link1, array($this, 'fixLinks'), $text);
		$text = preg_replace_callback($link2, array($this, 'fixLinks'), $text);
		
		$pattern = array(
			'/\[b\](.+?)\[\/b\]/si',
			'/\[i\](.+?)\[\/i\]/si',
			'/\[url=(.+?)\](.+?)\[\/url\]/si',
		);
		$replace = array(
			'<strong>$1</strong>',
			'<em>$1</em>',
			'<a href="$1">$2</a>'
		);
		
		$text = preg_replace($pattern, $replace, $text);
		
		return array(TRUE, $text);
	}
	
	function fixLinks($matches)
	{
		if (strtolower(substr($matches[1], 0, 7)) != 'http://')
			$matches[1] = 'http://'.$matches[1];
			
		return '<a href="'.$matches[1].'">'.$matches[2].'</a>';
	}
	
}